package online.hxstart.code.concurrent.chapter10;

/**
 * @author huxing
 * @date 2019/7/12 星期五 18:16
 * @describe 破坏双亲委托机制
 */
public class BrokerDelegateClassLoader extends MyClassLoader {


  public BrokerDelegateClassLoader(String classDir) {
    super(classDir);
  }

  @Override
  protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {

    synchronized (getClassLoadingLock(name)) {
      Class<?> klass = findLoadedClass(name);
      if (klass == null) {
        if (name.startsWith("java.") || name.startsWith("javax.")) {
          try {
            klass = getSystemClassLoader().loadClass(name);
          } catch (Exception ignored) {
          }
        } else {
          try {
            klass = this.findClass(name);
          } catch (ClassNotFoundException ignored) {
          }
          if (klass == null) {
            if (getParent() != null) {
              klass = getParent().loadClass(name);
            } else {
              klass = getSystemClassLoader().loadClass(name);
            }
          }
        }
      }
      if (klass == null) {
        throw new ClassNotFoundException("The class " + name + " not found.");
      }
      if (resolve) {
        resolveClass(klass);
      }
      return klass;
    }
  }
}
